/*
 * Postmore - a pop3 supported mailing list server;
 * Copyright (C) 2010 Peng Lei, pyp125@gmail.com
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 
 * details.
 *
 * You should have received a copy of the GNU Public License along with this
 * program. If not, see http://www.gnu.org/licenses/.
 */

#include "pmd.h"

void exec_thread(void* arg)
{
	/* Execute pm.exe -rc [configuration]; */
	execl("/usr/bin/pm.exe","-rc",(char*)arg);
}

int pid_file()
{
	pid_t pme=getpid();
	char* pmcfg=getenv("PM_CFG");
	char fpath[128];
	bzero(fpath,sizeof(fpath));
	sprintf(fpath,"%s/runtime.pid",pmcfg);
	FILE* _fpid;
	if(!(_fpid=fopen(fpath,"w")))
		return -1;
	fprintf(_fpid,"%d",pme);
	fclose(_fpid);
	return 0;
}

int main(int argc,char** argv)
{
	char cfgarg[128];
	FILE* _flist;
	/* Open configuration list; */
	if(!(_flist=fopen(getenv("PM_LIST"),"r")))
		exit(EXIT_FAILURE);
	/* Create pid file; */
	if(pid_file()<0)
		exit(EXIT_FAILURE);
	/* Configration reading, create threads; */
	while(fgets(cfgarg,sizeof(cfgarg),_flist))
	{
		pthread_t tid;
		pthread_create(&tid,NULL,(void*)exec_thread,(void*)cfgarg);
	}
	/* Close configuration list; */
	fclose(_flist);
	/* Block the main thread; */
	while(1)
		sleep(1);
    exit(EXIT_SUCCESS);
}
